import React, { useEffect } from 'react';
import { connect } from 'umi';
import { Spin, Message } from 'antd';
import moment from 'moment';

import { useStaticState, useTRState } from '#/utils/trHooks.jsx';
import { HttpCode } from '#/utils/contacts.js';
import { PageLoading } from '@/components';
import { TRDefault } from '@/components/index.js';
import { useExcel } from '@/hooks';
import { getParamObj, getTreeByCodes } from '@/utils/index.js';

import Header from './components/Header';
import styles from './index.less';
import Container from './components/Container';
import { queryMarketList, greenCertificateAnalysis } from './services';
import { orderDefault, orderMap } from './constant';
import { getTableData, tableColumns, initParam } from './helper';

const exportKey = 'GreenCertificateAnalysis';
const GreenCertificateAnalysis = ({ menuCode, buttonPermissions }) => {
  const [state, setState] = useTRState({
    canExport: buttonPermissions.some((item) => item.menuCode === exportKey),
    error: '',
    firstLoading: true,
    loading: false,
    power: [], // 数据权限
    dataSource: [],
    order: [...orderDefault], // 聚合维度（bind）
    tableData: [],
    exportTable: [],
    formValues: {}, //查询参数
  });
  const staticState = useStaticState({
    flag: false, //合约管理跳转
    isFirst: false, //默认请求
    str: null,
    contractOption: [],
  });

  useEffect(() => {
    staticState.isFirst = true;
    staticState.str = getParamObj();
    if (JSON.stringify(staticState.str) !== '{}') {
      staticState.flag = true;
      staticState.str = initParam(staticState.str);
    }
    fetchData();
  }, []);

  const fetchData = async () => {
    setState({ firstLoading: true });
    let error = '';
    let power = [];
    const res = await queryMarketList(menuCode);
    if (res?.statusCode === HttpCode.SUCCESS) {
      power = getTreeByCodes(['station'], res.json).treeOptions;
    } else {
      error = res?.message;
    }
    setState({
      error,
      power,
      firstLoading: false,
    });
  };

  const fetch = async (values) => {
    // 数据
    setState({
      loading: true,
    });
    const res = await greenCertificateAnalysis(
      values,
      order.map((t) => orderMap[t]),
    );
    const { tableData, exportTable } = getTableData(res?.data, order);
    setState({
      tableData,
      exportTable,
      formValues: values,
      loading: false,
    });
  };

  const _onExport = () => {
    // 导出
    if (!state.canExport) return Message.info('请联系管理员获取相关权限');
    useExcel({
      filename: `${moment().format('YYYY.MM.DD HH：mm：ss')} 绿证分析`,
      columns: tableColumns,
      data: state.exportTable,
    });
  };

  const { firstLoading, loading, power, error, tableData, order, formValues } = state;
  if (firstLoading) return <PageLoading />;
  if (error) return <TRDefault type="error" message={state.error} />;
  // if (!power.length) return <TRDefault type="lock" />;
  return (
    <div className={styles.body}>
      <Header
        power={power}
        loading={loading}
        initValues={staticState.str}
        onChange={fetch}
        onExport={_onExport}
      />
      <div className={styles.box}>
        <div className={styles.content}>
          {!tableData?.length ? (
            <TRDefault type={'empty'} />
          ) : (
            <Spin spinning={loading}>
              <Container
                loading={loading}
                tableData={tableData}
                onChange={() => {
                  fetch(formValues);
                }}
                order={state.order}
                setOrder={(v) => {
                  setState({ order: v });
                }}
                buttonPermissions={buttonPermissions}
                setLoading={(v) => {
                  setState({ loading: v });
                }}
              />
            </Spin>
          )}
        </div>
      </div>
    </div>
  );
};

export default connect(({ global }) => ({
  menuCode: global.configure.menuCode,
  buttonPermissions: global.configure.buttonPermissions,
}))(GreenCertificateAnalysis);
